package com.shanjupay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.xml.ws.Response;
import java.util.HashMap;
import java.util.Map;

/**
 * <h1>短信服务实现</h1>
 *
 * @author lsy
 * @date 2020/05/07
 */
@Slf4j
@org.springframework.stereotype.Service
public class SmsServiceImpl implements SmsService {

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取短信验证码
     *
     * @param phone
     * @return
     */
    @Override
    public String sendMsg(String phone) throws BusinessException {
        String sms_url = smsUrl + "/generate?name=sms&effectiveTime=" + effectiveTime;

        log.info("调用短信微服务发送验证码: url:{}", sms_url);

        Map<String, Object> body = new HashMap<>();
        body.put("mobile", phone);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity httpEntity = new HttpEntity(body, httpHeaders);

        ResponseEntity<Map> change = null;

        Map bodyMap = null;

        try {
            change = restTemplate.exchange(sms_url, HttpMethod.POST, httpEntity, Map.class);
            log.info("请求验证码服务，得到响应：{}", JSON.toJSONString(change));
            bodyMap = change.getBody();
        } catch (RestClientException e) {
            throw new BusinessException(CommonErrorCode.E_100107);
        }
        if (bodyMap == null || bodyMap.get("result") == null) {
            throw new BusinessException(CommonErrorCode.E_100107);
        }
        Map result = (Map) bodyMap.get("result");
        String key = (String) result.get("key");
        log.info("得到发送验证码对应的key: {}", key);
        return key;
    }

    /**
     * 验证码校验
     *
     * @param verifyKey  sms:xxxxxx
     * @param verifyCode 手机收到的验证码
     */
    @Override
    public void checkVerifyCode(String verifyKey, String verifyCode) throws BusinessException {
        String url = "http://localhost:56085/sailing/verify?name=sms&verificationCode="+verifyCode+"&verificationKey="+verifyKey;
        Map bodyMap = null;

        try {
            // 请求验证码服务
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            log.info("请求验证码服务，得到响应: {}", JSON.toJSONString(exchange));
            bodyMap = exchange.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_100102);
        }
        if (bodyMap == null || bodyMap.get("result") == null || !(Boolean) bodyMap.get("result")) {
            throw new BusinessException(CommonErrorCode.E_100102);
        }
    }
}
